home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / python-support / python-gdata / gdata / auth.py < prev    next >
Encoding:
Python Source  |  2008-12-03  |  35.7 KB  |  930 lines

  1. #!/usr/bin/python
  2. #
  3. # Copyright (C) 2007, 2008 Google Inc.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. #      http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16.  
  17.  
  18. import cgi
  19. import math
  20. import random
  21. import re
  22. import time
  23. import types
  24. import urllib
  25. import atom.http_interface
  26. import atom.token_store
  27. import atom.url
  28. import gdata.oauth as oauth
  29. import gdata.oauth.rsa as oauth_rsa
  30. import gdata.tlslite.utils.keyfactory as keyfactory
  31. import gdata.tlslite.utils.cryptomath as cryptomath
  32.  
  33. __author__ = 'api.jscudder (Jeff Scudder)'
  34.  
  35.  
  36. PROGRAMMATIC_AUTH_LABEL = 'GoogleLogin auth='
  37. AUTHSUB_AUTH_LABEL = 'AuthSub token='
  38.  
  39.  
  40. """This module provides functions and objects used with Google authentication.
  41.  
  42. Details on Google authorization mechanisms used with the Google Data APIs can
  43. be found here: 
  44. http://code.google.com/apis/gdata/auth.html
  45. http://code.google.com/apis/accounts/
  46.  
  47. The essential functions are the following.
  48. Related to ClientLogin:
  49.   generate_client_login_request_body: Constructs the body of an HTTP request to
  50.                                       obtain a ClientLogin token for a specific
  51.                                       service. 
  52.   extract_client_login_token: Creates a ClientLoginToken with the token from a
  53.                               success response to a ClientLogin request.
  54.   get_captcha_challenge: If the server responded to the ClientLogin request
  55.                          with a CAPTCHA challenge, this method extracts the
  56.                          CAPTCHA URL and identifying CAPTCHA token.
  57.  
  58. Related to AuthSub:
  59.   generate_auth_sub_url: Constructs a full URL for a AuthSub request. The 
  60.                          user's browser must be sent to this Google Accounts
  61.                          URL and redirected back to the app to obtain the
  62.                          AuthSub token.
  63.   extract_auth_sub_token_from_url: Once the user's browser has been 
  64.                                    redirected back to the web app, use this
  65.                                    function to create an AuthSubToken with
  66.                                    the correct authorization token and scope.
  67.   token_from_http_body: Extracts the AuthSubToken value string from the 
  68.                         server's response to an AuthSub session token upgrade
  69.                         request.
  70. """
  71.  
  72. def generate_client_login_request_body(email, password, service, source, 
  73.     account_type='HOSTED_OR_GOOGLE', captcha_token=None, 
  74.     captcha_response=None):
  75.   """Creates the body of the autentication request
  76.  
  77.   See http://code.google.com/apis/accounts/AuthForInstalledApps.html#Request
  78.   for more details.
  79.  
  80.   Args:
  81.     email: str
  82.     password: str
  83.     service: str
  84.     source: str
  85.     account_type: str (optional) Defaul is 'HOSTED_OR_GOOGLE', other valid
  86.         values are 'GOOGLE' and 'HOSTED'
  87.     captcha_token: str (optional)
  88.     captcha_response: str (optional)
  89.  
  90.   Returns:
  91.     The HTTP body to send in a request for a client login token.
  92.   """
  93.   # Create a POST body containing the user's credentials.
  94.   request_fields = {'Email': email,
  95.                     'Passwd': password,
  96.                     'accountType': account_type,
  97.                     'service': service,
  98.                     'source': source}
  99.   if captcha_token and captcha_response:
  100.     # Send the captcha token and response as part of the POST body if the
  101.     # user is responding to a captch challenge.
  102.     request_fields['logintoken'] = captcha_token
  103.     request_fields['logincaptcha'] = captcha_response
  104.   return urllib.urlencode(request_fields)
  105.  
  106.  
  107. GenerateClientLoginRequestBody = generate_client_login_request_body
  108.  
  109.  
  110. def GenerateClientLoginAuthToken(http_body):
  111.   """Returns the token value to use in Authorization headers.
  112.  
  113.   Reads the token from the server's response to a Client Login request and
  114.   creates header value to use in requests.
  115.  
  116.   Args:
  117.     http_body: str The body of the server's HTTP response to a Client Login
  118.         request
  119.  
  120.   Returns:
  121.     The value half of an Authorization header.
  122.   """
  123.   token = get_client_login_token(http_body)
  124.   if token:
  125.     return 'GoogleLogin auth=%s' % token
  126.   return None
  127.  
  128.  
  129. def get_client_login_token(http_body):
  130.   """Returns the token value for a ClientLoginToken.
  131.  
  132.   Reads the token from the server's response to a Client Login request and
  133.   creates the token value string to use in requests.
  134.  
  135.   Args:
  136.     http_body: str The body of the server's HTTP response to a Client Login
  137.         request
  138.  
  139.   Returns:
  140.     The token value string for a ClientLoginToken.
  141.   """
  142.   for response_line in http_body.splitlines():
  143.     if response_line.startswith('Auth='):
  144.       # Strip off the leading Auth= and return the Authorization value.
  145.       return response_line[5:]
  146.   return None
  147.  
  148.  
  149. def extract_client_login_token(http_body, scopes):
  150.   """Parses the server's response and returns a ClientLoginToken.
  151.   
  152.   Args:
  153.     http_body: str The body of the server's HTTP response to a Client Login
  154.                request. It is assumed that the login request was successful.
  155.     scopes: list containing atom.url.Urls or strs. The scopes list contains
  156.             all of the partial URLs under which the client login token is
  157.             valid. For example, if scopes contains ['http://example.com/foo']
  158.             then the client login token would be valid for 
  159.             http://example.com/foo/bar/baz
  160.  
  161.   Returns:
  162.     A ClientLoginToken which is valid for the specified scopes.
  163.   """
  164.   token_string = get_client_login_token(http_body)
  165.   token = ClientLoginToken(scopes=scopes)
  166.   token.set_token_string(token_string)
  167.   return token
  168.  
  169.  
  170. def get_captcha_challenge(http_body, 
  171.     captcha_base_url='http://www.google.com/accounts/'):
  172.   """Returns the URL and token for a CAPTCHA challenge issued by the server.
  173.  
  174.   Args:
  175.     http_body: str The body of the HTTP response from the server which 
  176.         contains the CAPTCHA challenge.
  177.     captcha_base_url: str This function returns a full URL for viewing the 
  178.         challenge image which is built from the server's response. This
  179.         base_url is used as the beginning of the URL because the server
  180.         only provides the end of the URL. For example the server provides
  181.         'Captcha?ctoken=Hi...N' and the URL for the image is
  182.         'http://www.google.com/accounts/Captcha?ctoken=Hi...N'
  183.  
  184.   Returns:
  185.     A dictionary containing the information needed to repond to the CAPTCHA
  186.     challenge, the image URL and the ID token of the challenge. The 
  187.     dictionary is in the form:
  188.     {'token': string identifying the CAPTCHA image,
  189.      'url': string containing the URL of the image}
  190.     Returns None if there was no CAPTCHA challenge in the response.
  191.   """
  192.   contains_captcha_challenge = False
  193.   captcha_parameters = {}
  194.   for response_line in http_body.splitlines():
  195.     if response_line.startswith('Error=CaptchaRequired'):
  196.       contains_captcha_challenge = True
  197.     elif response_line.startswith('CaptchaToken='):
  198.       # Strip off the leading CaptchaToken=
  199.       captcha_parameters['token'] = response_line[13:]
  200.     elif response_line.startswith('CaptchaUrl='):
  201.       captcha_parameters['url'] = '%s%s' % (captcha_base_url,
  202.           response_line[11:])
  203.   if contains_captcha_challenge:
  204.     return captcha_parameters
  205.   else:
  206.     return None
  207.  
  208.  
  209. GetCaptchaChallenge = get_captcha_challenge
  210.  
  211.  
  212. def GenerateOAuthRequestTokenUrl(
  213.     oauth_input_params, scopes,
  214.     request_token_url='https://www.google.com/accounts/OAuthGetRequestToken',
  215.     extra_parameters=None):
  216.   """Generate a URL at which a request for OAuth request token is to be sent.
  217.   
  218.   Args:
  219.     oauth_input_params: OAuthInputParams OAuth input parameters.
  220.     scopes: list of strings The URLs of the services to be accessed.
  221.     request_token_url: string The beginning of the request token URL. This is
  222.         normally 'https://www.google.com/accounts/OAuthGetRequestToken' or
  223.         '/accounts/OAuthGetRequestToken'
  224.     extra_parameters: dict (optional) key-value pairs as any additional
  225.         parameters to be included in the URL and signature while making a
  226.         request for fetching an OAuth request token. All the OAuth parameters
  227.         are added by default. But if provided through this argument, any
  228.         default parameters will be overwritten. For e.g. a default parameter
  229.         oauth_version 1.0 can be overwritten if
  230.         extra_parameters = {'oauth_version': '2.0'}
  231.   
  232.   Returns:
  233.     atom.url.Url OAuth request token URL.
  234.   """
  235.   scopes_string = ' '.join([str(scope) for scope in scopes])
  236.   parameters = {'scope': scopes_string}
  237.   if extra_parameters:
  238.     parameters.update(extra_parameters)
  239.   oauth_request = oauth.OAuthRequest.from_consumer_and_token(
  240.       oauth_input_params.GetConsumer(), http_url=request_token_url,
  241.       parameters=parameters)
  242.   oauth_request.sign_request(oauth_input_params.GetSignatureMethod(),
  243.                              oauth_input_params.GetConsumer(), None)
  244.   return atom.url.parse_url(oauth_request.to_url())
  245.  
  246.  
  247. def GenerateOAuthAuthorizationUrl(
  248.     request_token,
  249.     authorization_url='https://www.google.com/accounts/OAuthAuthorizeToken',
  250.     callback_url=None, extra_params=None,
  251.     include_scopes_in_callback=False, scopes_param_prefix='oauth_token_scope'):
  252.   """Generates URL at which user will login to authorize the request token.
  253.   
  254.   Args:
  255.     request_token: gdata.auth.OAuthToken OAuth request token.
  256.     authorization_url: string The beginning of the authorization URL. This is
  257.         normally 'https://www.google.com/accounts/OAuthAuthorizeToken' or
  258.         '/accounts/OAuthAuthorizeToken'
  259.     callback_url: string (optional) The URL user will be sent to after
  260.         logging in and granting access.
  261.     extra_params: dict (optional) Additional parameters to be sent.
  262.     include_scopes_in_callback: Boolean (default=False) if set to True, and
  263.         if 'callback_url' is present, the 'callback_url' will be modified to
  264.         include the scope(s) from the request token as a URL parameter. The
  265.         key for the 'callback' URL's scope parameter will be
  266.         OAUTH_SCOPE_URL_PARAM_NAME. The benefit of including the scope URL as
  267.         a parameter to the 'callback' URL, is that the page which receives
  268.         the OAuth token will be able to tell which URLs the token grants
  269.         access to.
  270.     scopes_param_prefix: string (default='oauth_token_scope') The URL
  271.         parameter key which maps to the list of valid scopes for the token.
  272.         This URL parameter will be included in the callback URL along with
  273.         the scopes of the token as value if include_scopes_in_callback=True.
  274.  
  275.   Returns:
  276.     atom.url.Url OAuth authorization URL.
  277.   """
  278.   scopes = request_token.scopes
  279.   if isinstance(scopes, list):
  280.     scopes = ' '.join(scopes)  
  281.   if include_scopes_in_callback and callback_url:
  282.     if callback_url.find('?') > -1:
  283.       callback_url += '&'
  284.     else:
  285.       callback_url += '?'
  286.     callback_url += urllib.urlencode({scopes_param_prefix:scopes})  
  287.   oauth_token = oauth.OAuthToken(request_token.key, request_token.secret)
  288.   oauth_request = oauth.OAuthRequest.from_token_and_callback(
  289.       token=oauth_token, callback=callback_url,
  290.       http_url=authorization_url, parameters=extra_params)
  291.   return atom.url.parse_url(oauth_request.to_url())
  292.  
  293.  
  294. def GenerateOAuthAccessTokenUrl(
  295.     authorized_request_token,
  296.     oauth_input_params,
  297.     access_token_url='https://www.google.com/accounts/OAuthGetAccessToken',
  298.     oauth_version='1.0'):
  299.   """Generates URL at which user will login to authorize the request token.
  300.   
  301.   Args:
  302.     authorized_request_token: gdata.auth.OAuthToken OAuth authorized request
  303.         token.
  304.     oauth_input_params: OAuthInputParams OAuth input parameters.    
  305.     access_token_url: string The beginning of the authorization URL. This is
  306.         normally 'https://www.google.com/accounts/OAuthGetAccessToken' or
  307.         '/accounts/OAuthGetAccessToken'
  308.     oauth_version: str (default='1.0') oauth_version parameter.
  309.  
  310.   Returns:
  311.     atom.url.Url OAuth access token URL.
  312.   """
  313.   oauth_token = oauth.OAuthToken(authorized_request_token.key,
  314.                                  authorized_request_token.secret)
  315.   oauth_request = oauth.OAuthRequest.from_consumer_and_token(
  316.       oauth_input_params.GetConsumer(), token=oauth_token,
  317.       http_url=access_token_url, parameters={'oauth_version': oauth_version})
  318.   oauth_request.sign_request(oauth_input_params.GetSignatureMethod(),
  319.                              oauth_input_params.GetConsumer(), oauth_token)
  320.   return atom.url.parse_url(oauth_request.to_url())
  321.  
  322.  
  323. def GenerateAuthSubUrl(next, scope, secure=False, session=True, 
  324.     request_url='https://www.google.com/accounts/AuthSubRequest',
  325.     domain='default'):
  326.   """Generate a URL at which the user will login and be redirected back.
  327.  
  328.   Users enter their credentials on a Google login page and a token is sent
  329.   to the URL specified in next. See documentation for AuthSub login at:
  330.   http://code.google.com/apis/accounts/AuthForWebApps.html
  331.  
  332.   Args:
  333.     request_url: str The beginning of the request URL. This is normally
  334.         'http://www.google.com/accounts/AuthSubRequest' or 
  335.         '/accounts/AuthSubRequest'
  336.     next: string The URL user will be sent to after logging in.
  337.     scope: string The URL of the service to be accessed.
  338.     secure: boolean (optional) Determines whether or not the issued token
  339.             is a secure token.
  340.     session: boolean (optional) Determines whether or not the issued token
  341.              can be upgraded to a session token.
  342.     domain: str (optional) The Google Apps domain for this account. If this
  343.             is not a Google Apps account, use 'default' which is the default
  344.             value.
  345.   """
  346.   # Translate True/False values for parameters into numeric values acceoted
  347.   # by the AuthSub service.
  348.   if secure:
  349.     secure = 1
  350.   else:
  351.     secure = 0
  352.  
  353.   if session:
  354.     session = 1
  355.   else:
  356.     session = 0
  357.  
  358.   request_params = urllib.urlencode({'next': next, 'scope': scope,
  359.                                      'secure': secure, 'session': session, 
  360.                                      'hd': domain})
  361.   if request_url.find('?') == -1:
  362.     return '%s?%s' % (request_url, request_params)
  363.   else:
  364.     # The request URL already contained url parameters so we should add
  365.     # the parameters using the & seperator
  366.     return '%s&%s' % (request_url, request_params)
  367.  
  368.  
  369. def generate_auth_sub_url(next, scopes, secure=False, session=True,
  370.     request_url='https://www.google.com/accounts/AuthSubRequest', 
  371.     domain='default', scopes_param_prefix='auth_sub_scopes'):
  372.   """Constructs a URL string for requesting a multiscope AuthSub token.
  373.  
  374.   The generated token will contain a URL parameter to pass along the 
  375.   requested scopes to the next URL. When the Google Accounts page 
  376.   redirects the broswser to the 'next' URL, it appends the single use
  377.   AuthSub token value to the URL as a URL parameter with the key 'token'.
  378.   However, the information about which scopes were requested is not
  379.   included by Google Accounts. This method adds the scopes to the next
  380.   URL before making the request so that the redirect will be sent to 
  381.   a page, and both the token value and the list of scopes can be 
  382.   extracted from the request URL. 
  383.  
  384.   Args:
  385.     next: atom.url.URL or string The URL user will be sent to after
  386.           authorizing this web application to access their data.
  387.     scopes: list containint strings The URLs of the services to be accessed.
  388.     secure: boolean (optional) Determines whether or not the issued token
  389.             is a secure token.
  390.     session: boolean (optional) Determines whether or not the issued token
  391.              can be upgraded to a session token.
  392.     request_url: atom.url.Url or str The beginning of the request URL. This
  393.         is normally 'http://www.google.com/accounts/AuthSubRequest' or 
  394.         '/accounts/AuthSubRequest'
  395.     domain: The domain which the account is part of. This is used for Google
  396.         Apps accounts, the default value is 'default' which means that the
  397.         requested account is a Google Account (@gmail.com for example)
  398.     scopes_param_prefix: str (optional) The requested scopes are added as a 
  399.         URL parameter to the next URL so that the page at the 'next' URL can
  400.         extract the token value and the valid scopes from the URL. The key
  401.         for the URL parameter defaults to 'auth_sub_scopes'
  402.  
  403.   Returns:
  404.     An atom.url.Url which the user's browser should be directed to in order
  405.     to authorize this application to access their information.
  406.   """
  407.   if isinstance(next, (str, unicode)):
  408.     next = atom.url.parse_url(next)
  409.   scopes_string = ' '.join([str(scope) for scope in scopes])
  410.   next.params[scopes_param_prefix] = scopes_string
  411.  
  412.   if isinstance(request_url, (str, unicode)):
  413.     request_url = atom.url.parse_url(request_url)
  414.   request_url.params['next'] = str(next)
  415.   request_url.params['scope'] = scopes_string
  416.   if session:
  417.     request_url.params['session'] = 1
  418.   else:
  419.     request_url.params['session'] = 0
  420.   if secure:
  421.     request_url.params['secure'] = 1
  422.   else:
  423.     request_url.params['secure'] = 0
  424.   request_url.params['hd'] = domain
  425.   return request_url
  426.  
  427.  
  428. def AuthSubTokenFromUrl(url):
  429.   """Extracts the AuthSub token from the URL. 
  430.  
  431.   Used after the AuthSub redirect has sent the user to the 'next' page and
  432.   appended the token to the URL. This function returns the value to be used
  433.   in the Authorization header. 
  434.  
  435.   Args:
  436.     url: str The URL of the current page which contains the AuthSub token as
  437.         a URL parameter.
  438.   """
  439.   token = TokenFromUrl(url)
  440.   if token:
  441.     return 'AuthSub token=%s' % token
  442.   return None
  443.  
  444.  
  445. def TokenFromUrl(url):
  446.   """Extracts the AuthSub token from the URL.
  447.  
  448.   Returns the raw token value.
  449.  
  450.   Args:
  451.     url: str The URL or the query portion of the URL string (after the ?) of
  452.         the current page which contains the AuthSub token as a URL parameter.
  453.   """
  454.   if url.find('?') > -1:
  455.     query_params = url.split('?')[1]
  456.   else:
  457.     query_params = url
  458.   for pair in query_params.split('&'):
  459.     if pair.startswith('token='):
  460.       return pair[6:]
  461.   return None
  462.  
  463.  
  464. def extract_auth_sub_token_from_url(url, 
  465.     scopes_param_prefix='auth_sub_scopes', rsa_key=None):
  466.   """Creates an AuthSubToken and sets the token value and scopes from the URL.
  467.   
  468.   After the Google Accounts AuthSub pages redirect the user's broswer back to 
  469.   the web application (using the 'next' URL from the request) the web app must
  470.   extract the token from the current page's URL. The token is provided as a 
  471.   URL parameter named 'token' and if generate_auth_sub_url was used to create
  472.   the request, the token's valid scopes are included in a URL parameter whose
  473.   name is specified in scopes_param_prefix.
  474.  
  475.   Args:
  476.     url: atom.url.Url or str representing the current URL. The token value
  477.          and valid scopes should be included as URL parameters.
  478.     scopes_param_prefix: str (optional) The URL parameter key which maps to
  479.                          the list of valid scopes for the token.
  480.  
  481.   Returns:
  482.     An AuthSubToken with the token value from the URL and set to be valid for
  483.     the scopes passed in on the URL. If no scopes were included in the URL,
  484.     the AuthSubToken defaults to being valid for no scopes. If there was no
  485.     'token' parameter in the URL, this function returns None.
  486.   """
  487.   if isinstance(url, (str, unicode)):
  488.     url = atom.url.parse_url(url)
  489.   if 'token' not in url.params:
  490.     return None
  491.   scopes = []
  492.   if scopes_param_prefix in url.params:
  493.     scopes = url.params[scopes_param_prefix].split(' ')
  494.   token_value = url.params['token']
  495.   if rsa_key:
  496.     token = SecureAuthSubToken(rsa_key, scopes=scopes)
  497.   else:
  498.     token = AuthSubToken(scopes=scopes)
  499.   token.set_token_string(token_value)
  500.   return token
  501.  
  502.  
  503. def AuthSubTokenFromHttpBody(http_body):
  504.   """Extracts the AuthSub token from an HTTP body string.
  505.  
  506.   Used to find the new session token after making a request to upgrade a
  507.   single use AuthSub token.
  508.  
  509.   Args:
  510.     http_body: str The repsonse from the server which contains the AuthSub
  511.         key. For example, this function would find the new session token
  512.         from the server's response to an upgrade token request.
  513.  
  514.   Returns:
  515.     The header value to use for Authorization which contains the AuthSub
  516.     token.
  517.   """
  518.   token_value = token_from_http_body(http_body)
  519.   if token_value:
  520.     return '%s%s' % (AUTHSUB_AUTH_LABEL, token_value)
  521.   return None
  522.  
  523.  
  524. def token_from_http_body(http_body):
  525.   """Extracts the AuthSub token from an HTTP body string.
  526.  
  527.   Used to find the new session token after making a request to upgrade a 
  528.   single use AuthSub token.
  529.  
  530.   Args:
  531.     http_body: str The repsonse from the server which contains the AuthSub 
  532.         key. For example, this function would find the new session token
  533.         from the server's response to an upgrade token request.
  534.  
  535.   Returns:
  536.     The raw token value to use in an AuthSubToken object.
  537.   """
  538.   for response_line in http_body.splitlines():
  539.     if response_line.startswith('Token='):
  540.       # Strip off Token= and return the token value string.
  541.       return response_line[6:]
  542.   return None
  543.  
  544.  
  545. TokenFromHttpBody = token_from_http_body
  546.  
  547.  
  548. def OAuthTokenFromUrl(url, scopes_param_prefix='oauth_token_scope'):
  549.   """Creates an OAuthToken and sets token key and scopes (if present) from URL.
  550.   
  551.   After the Google Accounts OAuth pages redirect the user's broswer back to 
  552.   the web application (using the 'callback' URL from the request) the web app
  553.   can extract the token from the current page's URL. The token is same as the
  554.   request token, but it is either authorized (if user grants access) or
  555.   unauthorized (if user denies access). The token is provided as a 
  556.   URL parameter named 'oauth_token' and if it was chosen to use
  557.   GenerateOAuthAuthorizationUrl with include_scopes_in_param=True, the token's
  558.   valid scopes are included in a URL parameter whose name is specified in
  559.   scopes_param_prefix.
  560.  
  561.   Args:
  562.     url: atom.url.Url or str representing the current URL. The token value
  563.         and valid scopes should be included as URL parameters.
  564.     scopes_param_prefix: str (optional) The URL parameter key which maps to
  565.         the list of valid scopes for the token.
  566.  
  567.   Returns:
  568.     An OAuthToken with the token key from the URL and set to be valid for
  569.     the scopes passed in on the URL. If no scopes were included in the URL,
  570.     the OAuthToken defaults to being valid for no scopes. If there was no
  571.     'oauth_token' parameter in the URL, this function returns None.
  572.   """
  573.   if isinstance(url, (str, unicode)):
  574.     url = atom.url.parse_url(url)
  575.   if 'oauth_token' not in url.params:
  576.     return None
  577.   scopes = []
  578.   if scopes_param_prefix in url.params:
  579.     scopes = url.params[scopes_param_prefix].split(' ')
  580.   token_key = url.params['oauth_token']
  581.   token = OAuthToken(key=token_key, scopes=scopes)
  582.   return token
  583.  
  584.  
  585. def OAuthTokenFromHttpBody(http_body):
  586.   """Parses the HTTP response body and returns an OAuth token.
  587.   
  588.   The returned OAuth token will just have key and secret parameters set.
  589.   It won't have any knowledge about the scopes or oauth_input_params. It is
  590.   your responsibility to make it aware of the remaining parameters.
  591.   
  592.   Returns:
  593.     OAuthToken OAuth token.
  594.   """
  595.   token = oauth.OAuthToken.from_string(http_body)
  596.   oauth_token = OAuthToken(key=token.key, secret=token.secret)
  597.   return oauth_token
  598.   
  599.  
  600. class OAuthSignatureMethod(object):
  601.   """Holds valid OAuth signature methods.
  602.   
  603.   RSA_SHA1: Class to build signature according to RSA-SHA1 algorithm.
  604.   HMAC_SHA1: Class to build signature according to HMAC-SHA1 algorithm.
  605.   """
  606.   
  607.   HMAC_SHA1 = oauth.OAuthSignatureMethod_HMAC_SHA1  
  608.   
  609.   class RSA_SHA1(oauth_rsa.OAuthSignatureMethod_RSA_SHA1):
  610.     """Provides implementation for abstract methods to return RSA certs."""
  611.  
  612.     def __init__(self, private_key, public_cert):
  613.       self.private_key = private_key
  614.       self.public_cert = public_cert
  615.   
  616.     def _fetch_public_cert(self, unused_oauth_request):
  617.       return self.public_cert
  618.   
  619.     def _fetch_private_cert(self, unused_oauth_request):
  620.       return self.private_key
  621.   
  622.  
  623. class OAuthInputParams(object):
  624.   """Stores OAuth input parameters.
  625.   
  626.   This class is a store for OAuth input parameters viz. consumer key and secret,
  627.   signature method and RSA key.
  628.   """
  629.   
  630.   def __init__(self, signature_method, consumer_key, consumer_secret=None,
  631.                rsa_key=None):
  632.     """Initializes object with parameters required for using OAuth mechanism.
  633.     
  634.     NOTE: Though consumer_secret and rsa_key are optional, either of the two
  635.     is required depending on the value of the signature_method.
  636.     
  637.     Args:
  638.       signature_method: class which provides implementation for strategy class
  639.           oauth.oauth.OAuthSignatureMethod. Signature method to be used for
  640.           signing each request. Valid implementations are provided as the
  641.           constants defined by gdata.auth.OAuthSignatureMethod. Currently
  642.           they are gdata.auth.OAuthSignatureMethod.RSA_SHA1 and
  643.           gdata.auth.OAuthSignatureMethod.HMAC_SHA1
  644.       consumer_key: string Domain identifying third_party web application.
  645.       consumer_secret: string (optional) Secret generated during registration.
  646.           Required only for HMAC_SHA1 signature method.
  647.       rsa_key: string (optional) Private key required for RSA_SHA1 signature
  648.           method.
  649.     """
  650.     if signature_method == OAuthSignatureMethod.RSA_SHA1:
  651.       self._signature_method = signature_method(rsa_key, None)
  652.     else:
  653.       self._signature_method = signature_method()
  654.     self._consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)
  655.     
  656.   def GetSignatureMethod(self):
  657.     """Gets the OAuth signature method.
  658.  
  659.     Returns:
  660.       object of supertype <oauth.oauth.OAuthSignatureMethod>
  661.     """
  662.     return self._signature_method
  663.   
  664.   def GetConsumer(self):
  665.     """Gets the OAuth consumer.
  666.     
  667.     Returns:
  668.       object of type <oauth.oauth.Consumer>
  669.     """
  670.     return self._consumer
  671.  
  672.  
  673. class ClientLoginToken(atom.http_interface.GenericToken):
  674.   """Stores the Authorization header in auth_header and adds to requests.
  675.  
  676.   This token will add it's Authorization header to an HTTP request
  677.   as it is made. Ths token class is simple but
  678.   some Token classes must calculate portions of the Authorization header
  679.   based on the request being made, which is why the token is responsible
  680.   for making requests via an http_client parameter.
  681.  
  682.   Args:
  683.     auth_header: str The value for the Authorization header.
  684.     scopes: list of str or atom.url.Url specifying the beginnings of URLs
  685.         for which this token can be used. For example, if scopes contains
  686.         'http://example.com/foo', then this token can be used for a request to
  687.         'http://example.com/foo/bar' but it cannot be used for a request to
  688.         'http://example.com/baz'
  689.   """
  690.   def __init__(self, auth_header=None, scopes=None):
  691.     self.auth_header = auth_header
  692.     self.scopes = scopes or []
  693.  
  694.   def __str__(self):
  695.     return self.auth_header
  696.  
  697.   def perform_request(self, http_client, operation, url, data=None,
  698.                       headers=None):
  699.     """Sets the Authorization header and makes the HTTP request."""
  700.     if headers is None:
  701.       headers = {'Authorization':self.auth_header}
  702.     else:
  703.       headers['Authorization'] = self.auth_header
  704.     return http_client.request(operation, url, data=data, headers=headers)
  705.  
  706.   def get_token_string(self):
  707.     """Removes PROGRAMMATIC_AUTH_LABEL to give just the token value."""
  708.     return self.auth_header[len(PROGRAMMATIC_AUTH_LABEL):]
  709.  
  710.   def set_token_string(self, token_string):
  711.     self.auth_header = '%s%s' % (PROGRAMMATIC_AUTH_LABEL, token_string)
  712.   
  713.   def valid_for_scope(self, url):
  714.     """Tells the caller if the token authorizes access to the desired URL.
  715.     """
  716.     if isinstance(url, (str, unicode)):
  717.       url = atom.url.parse_url(url)
  718.     for scope in self.scopes:
  719.       if scope == atom.token_store.SCOPE_ALL:
  720.         return True
  721.       if isinstance(scope, (str, unicode)):
  722.         scope = atom.url.parse_url(scope)
  723.       if scope == url:
  724.         return True
  725.       # Check the host and the path, but ignore the port and protocol.
  726.       elif scope.host == url.host and not scope.path:
  727.         return True
  728.       elif scope.host == url.host and scope.path and not url.path:
  729.         continue
  730.       elif scope.host == url.host and url.path.startswith(scope.path):
  731.         return True
  732.     return False
  733.  
  734.  
  735. class AuthSubToken(ClientLoginToken):
  736.   def get_token_string(self):
  737.     """Removes AUTHSUB_AUTH_LABEL to give just the token value."""
  738.     return self.auth_header[len(AUTHSUB_AUTH_LABEL):]
  739.  
  740.   def set_token_string(self, token_string):
  741.     self.auth_header = '%s%s' % (AUTHSUB_AUTH_LABEL, token_string)
  742.  
  743.  
  744. class OAuthToken(atom.http_interface.GenericToken):
  745.   """Stores the token key, token secret and scopes for which token is valid.
  746.   
  747.   This token adds the authorization header to each request made. It
  748.   re-calculates authorization header for every request since the OAuth
  749.   signature to be added to the authorization header is dependent on the
  750.   request parameters.
  751.   
  752.   Attributes:
  753.     key: str The value for the OAuth token i.e. token key.
  754.     secret: str The value for the OAuth token secret.
  755.     scopes: list of str or atom.url.Url specifying the beginnings of URLs
  756.         for which this token can be used. For example, if scopes contains
  757.         'http://example.com/foo', then this token can be used for a request to
  758.         'http://example.com/foo/bar' but it cannot be used for a request to
  759.         'http://example.com/baz'
  760.     oauth_input_params: OAuthInputParams OAuth input parameters.      
  761.   """
  762.   
  763.   def __init__(self, key=None, secret=None, scopes=None,
  764.                oauth_input_params=None):
  765.     self.key = key
  766.     self.secret = secret
  767.     self.scopes = scopes or []
  768.     self.oauth_input_params = oauth_input_params
  769.   
  770.   def __str__(self):
  771.     return self.get_token_string()
  772.  
  773.   def get_token_string(self):
  774.     """Returns the token string.
  775.     
  776.     The token string returned is of format
  777.     oauth_token=[0]&oauth_token_secret=[1], where [0] and [1] are some strings.
  778.     
  779.     Returns:
  780.       A token string of format oauth_token=[0]&oauth_token_secret=[1],
  781.       where [0] and [1] are some strings. If self.secret is absent, it just
  782.       returns oauth_token=[0]. If self.key is absent, it just returns
  783.       oauth_token_secret=[1]. If both are absent, it returns None.
  784.     """
  785.     if self.key and self.secret:
  786.       return urllib.urlencode({'oauth_token': self.key,
  787.                                'oauth_token_secret': self.secret})
  788.     elif self.key:
  789.       return 'oauth_token=%s' % self.key
  790.     elif self.secret:
  791.       return 'oauth_token_secret=%s' % self.secret
  792.     else:
  793.       return None
  794.  
  795.   def set_token_string(self, token_string):
  796.     """Sets the token key and secret from the token string.
  797.     
  798.     Args:
  799.       token_string: str Token string of form
  800.           oauth_token=[0]&oauth_token_secret=[1]. If oauth_token is not present,
  801.           self.key will be None. If oauth_token_secret is not present,
  802.           self.secret will be None.
  803.     """
  804.     token_params = cgi.parse_qs(token_string, keep_blank_values=False)
  805.     if 'oauth_token' in token_params:
  806.       self.key = token_params['oauth_token'][0]
  807.     if 'oauth_token_secret' in token_params:
  808.       self.secret = token_params['oauth_token_secret'][0]
  809.     
  810.   def GetAuthHeader(self, http_method, http_url, realm=''):
  811.     """Get the authentication header.
  812.  
  813.     Args:
  814.       http_method: string HTTP method i.e. operation e.g. GET, POST, PUT, etc.
  815.       http_url: string or atom.url.Url HTTP URL to which request is made.
  816.       realm: string (default='') realm parameter to be included in the
  817.           authorization header.
  818.  
  819.     Returns:
  820.       dict Header to be sent with every subsequent request after
  821.       authentication.
  822.     """
  823.     if isinstance(http_url, types.StringTypes):
  824.       http_url = atom.url.parse_url(http_url)
  825.     header = None
  826.     token = None
  827.     if self.key or self.secret:
  828.       token = oauth.OAuthToken(self.key, self.secret)
  829.     oauth_request = oauth.OAuthRequest.from_consumer_and_token(
  830.         self.oauth_input_params.GetConsumer(), token=token,
  831.         http_url=str(http_url), http_method=http_method,
  832.         parameters=http_url.params)
  833.     oauth_request.sign_request(self.oauth_input_params.GetSignatureMethod(),
  834.                                self.oauth_input_params.GetConsumer(), token)
  835.     header = oauth_request.to_header(realm=realm)
  836.     header['Authorization'] = header['Authorization'].replace('+', '%2B')
  837.     return header
  838.   
  839.   def perform_request(self, http_client, operation, url, data=None, 
  840.                       headers=None):
  841.     """Sets the Authorization header and makes the HTTP request."""
  842.     if not headers:
  843.       headers = {}
  844.     headers.update(self.GetAuthHeader(operation, url))
  845.     return http_client.request(operation, url, data=data, headers=headers)
  846.     
  847.   def valid_for_scope(self, url):
  848.     if isinstance(url, (str, unicode)):
  849.       url = atom.url.parse_url(url)
  850.     for scope in self.scopes:
  851.       if scope == atom.token_store.SCOPE_ALL:
  852.         return True
  853.       if isinstance(scope, (str, unicode)):
  854.         scope = atom.url.parse_url(scope)
  855.       if scope == url:
  856.         return True
  857.       # Check the host and the path, but ignore the port and protocol.
  858.       elif scope.host == url.host and not scope.path:
  859.         return True
  860.       elif scope.host == url.host and scope.path and not url.path:
  861.         continue
  862.       elif scope.host == url.host and url.path.startswith(scope.path):
  863.         return True
  864.     return False    
  865.     
  866.  
  867. class SecureAuthSubToken(AuthSubToken):
  868.   """Stores the rsa private key, token, and scopes for the secure AuthSub token.
  869.   
  870.   This token adds the authorization header to each request made. It
  871.   re-calculates authorization header for every request since the secure AuthSub
  872.   signature to be added to the authorization header is dependent on the
  873.   request parameters.
  874.   
  875.   Attributes:
  876.     rsa_key: string The RSA private key in PEM format that the token will
  877.              use to sign requests
  878.     token_string: string (optional) The value for the AuthSub token.
  879.     scopes: list of str or atom.url.Url specifying the beginnings of URLs
  880.         for which this token can be used. For example, if scopes contains
  881.         'http://example.com/foo', then this token can be used for a request to
  882.         'http://example.com/foo/bar' but it cannot be used for a request to
  883.         'http://example.com/baz'     
  884.   """
  885.   
  886.   def __init__(self, rsa_key, token_string=None, scopes=None):
  887.     self.rsa_key = keyfactory.parsePEMKey(rsa_key)
  888.     self.token_string = token_string or ''
  889.     self.scopes = scopes or [] 
  890.    
  891.   def __str__(self):
  892.     return self.get_token_string()
  893.  
  894.   def get_token_string(self):
  895.     return str(self.token_string)
  896.  
  897.   def set_token_string(self, token_string):
  898.     self.token_string = token_string
  899.     
  900.   def GetAuthHeader(self, http_method, http_url):
  901.     """Generates the Authorization header.
  902.  
  903.     The form of the secure AuthSub Authorization header is
  904.     Authorization: AuthSub token="token" sigalg="sigalg" data="data" sig="sig"
  905.     and  data represents a string in the form
  906.     data = http_method http_url timestamp nonce
  907.  
  908.     Args:
  909.       http_method: string HTTP method i.e. operation e.g. GET, POST, PUT, etc.
  910.       http_url: string or atom.url.Url HTTP URL to which request is made.
  911.       
  912.     Returns:
  913.       dict Header to be sent with every subsequent request after authentication.
  914.     """
  915.     timestamp = int(math.floor(time.time()))
  916.     nonce = '%lu' % random.randrange(1, 2**64)
  917.     data = '%s %s %d %s' % (http_method, str(http_url), timestamp, nonce)
  918.     sig = cryptomath.bytesToBase64(self.rsa_key.hashAndSign(data))
  919.     header = {'Authorization': '%s"%s" data="%s" sig="%s" sigalg="rsa-sha1"' %
  920.               (AUTHSUB_AUTH_LABEL, self.token_string, data, sig)}
  921.     return header
  922.   
  923.   def perform_request(self, http_client, operation, url, data=None, 
  924.                       headers=None):
  925.     """Sets the Authorization header and makes the HTTP request."""
  926.     if not headers:
  927.       headers = {}
  928.     headers.update(self.GetAuthHeader(operation, url))
  929.     return http_client.request(operation, url, data=data, headers=headers)
  930.